package com.tinymall.security;


import com.tinymall.common.pojo.vo.UserVO;
import com.tinymall.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("根据用户名查询尝试登录的管理员信息，用户名=" + username);
        UserVO userVO = userMapper.selectUserByUsername(username);
        System.out.println("通过持久层进行查询，结果=" + userVO);
        if (userVO == null) {
            System.out.println("根据用户名没有查询到有效的管理员数据，将抛出异常");
            throw new BadCredentialsException("登录失败，用户名不存在！");
        }

        System.out.println("查询到匹配的管理员数据，需要将此数据转换为UserDetails并返回");
        // 根据数据库查询的对象来封装成UserDetails
        UserDetails userDetails = User.builder()
                .username(userVO.getUsername())
                .password(userVO.getPassword())
                .accountExpired(false)
                .accountLocked(false)
                .disabled(userVO.getStatus() != 1)
                .credentialsExpired(false)
                .authorities(userVO.getRole())
                .build();
        System.out.println(userDetails);
        return userDetails;
    }
}
